export class StringUtils {
    static random(length:number, chars:string="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){
        var result = '';
        for (var i = length; i > 0; --i) {
            result += chars[Math.floor(Math.random() * chars.length)];
        }
        return result;
    }
    /**
     * 判断是否是远程资源
     * @param url 
     * @returns 
     */
    static isRemote(url: string): boolean {
        if(url.indexOf("http://") == 0 || url.indexOf("https://") == 0 ){
            return true;
        }
        return false;
    }
    /**
     * 是否为空
     * @param str 
     */
    public static isEmpty(str: string): boolean {
        if (str == null || str == undefined || str.length == 0) {
            return true;
        }
        return false;
    }

    /** 
    * 替换全部字符串 
    * @param string src 源串 
    * @param string from_ch 被替换的字符 
    * @param string to_ch 替换的字符 
    *  
    * @return string 结果字符串 
    */
    public static replaceAll(src: string, from_ch: string, to_ch: string): string {
        let regExp = new RegExp(from_ch, "g");
        return src.replace(regExp, to_ch);
    }

    /**
     * 参数替换
     *  @param  str
     *  @param  rest
     *  
     *  @example
     *
     *  var str:string = "here is some info '{0}' and {1}";
     *  trace(StringUtil.substitute(str, 15.4, true));
     *
     *  // this will output the following string:
     *  // "here is some info '15.4' and true"
     */
    public static format(str: string, ...rest:any[]): string {
        if (str == null) return '';

        // Replace all of the parameters in the msg string.
        var len: number = rest.length;
        var args: any[];
        if (len == 1 && rest[0] instanceof Array) {
            args = rest[0];
            len = args.length;
        }
        else {
            args = rest;
        }

        for (var i: number = 0; i < len; i++) {
            str = str.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]);
        }

        return str;
    }

    /**
     * 
     * 格式化数字
     * @param amount 目标数字
     * @param format 支持{1:"", 100:"百", 1000:"千", 10000:"万", 100000:"十万", 1000000:"百万", 10000000:"千万", 100000000:"亿", 1000000000000:"兆"}等
     * @returns 
     */
    public static formatNumber(amount:number, format): string {
        if(!format || amount == 0){
            return `${amount}`;
        }
        let formatKey:number[] = [];
        for (const key in format) {
            if (format.hasOwnProperty(key)) {
                formatKey.push(Number(key));
            }
        }
        if(!formatKey || formatKey.length == 0){
            return `${amount}`;
        }
        formatKey.sort((a, b)=>b-a);
        let result:string[] = [];
        let total:number = amount;
        for (let i = 0; i < formatKey.length; i++) {
            const key = formatKey[i];
            let count = Math.floor(Math.abs(total / key)) * (total / Math.abs(total));
            if(count == 0){
                continue;
            }
            total = total % key;
            result.push(`${count}${format[key]}`);
        }

        return result.length ? result.join("") : `${amount}`;
    }

    /**
     * 带自动补全的秒数格式。
     * @param second 秒数
     * @param format 格式化文本
     * @param pad 填充文本，默认为“0”
     * @example
     * formatSecond(86400, "ddd天hh小时mm分ss秒")=>"001天00小时00分00秒"
     * formatSecond(86400, "dd天hh小时mm分ss秒")=>"01天00小时00分00秒"
     * formatSecond(86400, "hh小时mm分ss秒")=>"24小时00分00秒"
     * formatSecond(86400, "mm分ss秒")=>"1440分00秒"
     * @returns 
     */
    static formatSecond(second: number, format:string, pad:string="0"):string {
        const formatArr = [
            {unit:86400, regExp:/D{2,}/i},
            {unit:3600, regExp:/H{1,2}/i},
            {unit:60, regExp:/m{1,2}/i},
            {unit:1, regExp:/s{1,2}/i},
        ];
        for (let i = 0; i < formatArr.length; i++) {
            const element = formatArr[i];
            let match = element.regExp.exec(format);
            if(match){
                format = format.replace(element.regExp, Math.floor(second / element.unit).toFixed(0).padStart(match[0].length, pad));
                second = second % element.unit;
            }
        }
        return format;
    }

    /**
     * 带自动补全的时间戳格式化
     * @param milliseconds 
     * @param format 
     * @param pad 填充文本，默认为“0”
     * @returns 
     */
    static formatTimestamp(milliseconds:number, format:string, pad:string="0"):string {
        let date = new Date(milliseconds);
        date.getHours()
        const formatArr = [
            {r:/Y{4}/, to:date.getFullYear()},
            {r:/M{1,2}/, to:date.getMonth() + 1},
            {r:/D{1,2}/, to:date.getDate()},
            {r:/H{1,2}/, to:date.getHours()},
            {r:/m{1,2}/, to:date.getMinutes()},
            {r:/s{1,2}/, to:date.getSeconds()},
        ];
        for (let i = 0; i < formatArr.length; i++) {
            const element = formatArr[i];
            let match = element.r.exec(format);
            if(match){
                format = format.replace(element.r, element.to.toString().padStart(match[0].length, "0"));
            }
        }
        return format;
    }
}
